<template>
	<yd-layout id='liveRoom' class='' :style='{background:navActiveNum==3?"#FCF9FC":"white"}'>
		<div slot='top'>
			<div class="live_room" ref='csRef' :style="videoStyle">
				<div v-if='!outImg' class="live_room_c" @click='playVideo'>
					<div class="mengban" v-show="playBtn"></div>

					<div :style="mengBanImgStyle"  class="mengbanimg" v-show="playBtn"></div>
					<img class="live_room_img_1" v-show='playBtn' src="../../assets/playBtn.png" alt="" />
					<!--:poster="liveInfo.title_img"-->
					<!-- x5-video-orientation="portraint" -->
					<!--x5-video-player-type="h5"-->
					<video @ended="endedVideo" 
						@pause="pauseVideo" 
						@playing='playIngVideo'
						 id="test_video" width="100%"
						  ref='videoRef' 
						  x5-video-orientation="portraint"
						  
						  height="30%" 
						  webkit-playsinline="true" 
						  playsinline="" x5-playsinline="" 
						  x-webkit-airplay="allow" 
						  :src="liveInfo.hls" 
						  :style="videoStyle" preload="" class="content text_left" style="position:inherit;width:100%;">
					</video>
				</div>
				<div v-else>
					<img :style="videoStyle" class="live_room_img_2" :src="liveInfo.title_img" alt="" />
					<div class="out_msg">{{outImgMsg}}</div>
				</div>
			</div>
			<ul class="nav">
				<li @click="navActive(1)" :class="navActiveNum==1?'nav_active':''">
					<span>直播介绍</span>
					<i></i>
				</li>
				<li @click="navActive(2)" :class="navActiveNum==2?'nav_active':''">
					<span>直播聊天</span>
					<i></i>
				</li>
				<li @click="navActive(3)" :class="navActiveNum==3?'nav_active':''">
					<span>礼物榜</span>
					<i></i>
				</li>
			</ul>
		</div>
		<div class="list_1" v-show="navActiveNum==1">
			<div v-if="false" class="list_1_top">
				<div class="list_1_title c_size_34_48">主讲老师</div>
				<div class="list_1_top_bottom">
					<img class="teacher_img" :src="liveInfo.avatar" alt="" />
					<div class="teacher">
						<div class="teacher_name c_size_30_42 c_text_ellipsis_1">{{liveInfo.nick_name}}</div>
						<div class="teacher_detail">{{liveInfo.summary}}</div>
					</div>
				</div>
			</div>

			<div class="list_html">
				<div v-if="false" class="title c_size_34_48">直播介绍</div>

				<template v-if="liveInfo.detail">
					<div class="c_v_html" v-html="liveInfo.detail">{{liveInfo.detail}}</div>
				</template>
				<div v-else class="no_detail">
					暂无直播介绍
				</div>

			</div>
		</div>
		<div class="list_2_f" v-show="navActiveNum==2" ref='messageListRef'>
			<div class="list_2" ref='messageListRefC'>
				<div class="list_2_list" :key='index' v-for="(message,index) in messageList">
					<!--非VIP-->
					<div v-if="message.msgType=='RC:TxtMsg'||message.msgType=='RC:MemberTxtMsg'">
						<span style="color: #79d5ff;">{{message.name}}</span>{{message.content}}
					</div>
					<div v-else-if="message.msgType=='RC:InfoNtf'">
						<span style="color: #999999;">{{message.content}}</span>
					</div>
					<!--VIP-->
					<div class="list_2_vip" v-else-if='message.msgType=="RC:MemberTxtMsg"'>
						<img class="list_2_vip_img" src="../../assets/vip_2.png" alt="" />
						<span class="span">{{message.name}}</span>
						<span for="" style="color: #FDBD5D;">{{message.content}}</span>
					</div>
					<!--礼物-->
					<div v-else-if='message.msgType=="RC:GiftMsg"' class='liwu_f'>
						<div class="liwu">
							<div class="liwu_name c_text_ellipsis_1">{{message.name}}</div>
							<span class="liwu_label">赠送{{message.content}}</span>
							<img :src="message.giftImg" alt="" />
						</div>
					</div>
					<!--NoticeMsg-->
					<div v-else-if='message.msgType=="RC:NoticeMsg"' class="list_2_zj">
						<div class="list_2_zj_f">
							<div class="list_2_zj_name c_text_ellipsis_1">恭喜{{message.user_name}}</div>
							<div class="list_2_zj_label">成为幸运观众</div>
						</div>
					</div>
				</div>
			</div>
			<div class="msg_num_f" v-show="msgNum>0">
				<div @click="goBottom" class="msg_num">有{{msgNum}}条新消息</div>
			</div>
		</div>

		<yd-infinitescroll v-show="navActiveNum==3" :callback="getRoomMembers" ref="infinitescrollDemo">

			<div class="list_3" slot="list">
				<!--members-->
				<div class="list_3_list" v-for="item,index in members">
					<div class="list_3_list_left">
						<div v-if="index>2" class="list_3_list_num">{{index+1}}</div>
						<img class="list_3_list_num_img" v-else-if="index==0" src="../../assets/liveRoom_1.png" alt="" />
						<img class="list_3_list_num_img" v-else-if="index==1" src="../../assets/liveRoom_2.png" alt="" />
						<img class="list_3_list_num_img" v-else-if="index==2" src="../../assets/liveRoom_3.png" alt="" />

					</div>
					<div class="list_3_list_people">
						<img class="list_3_list_people_img" :src="item.avatar" alt="" />
						<div class="list_3_list_people_name c_text_ellipsis_1">{{item.nick_name}}</div>
					</div>

					<div class="list_3_list_money">{{item.money}}</div>
				</div>
			</div>
			<!-- 数据全部加载完毕显示 -->
			<span slot="doneTip">没有更多数据了~~</span>

			<!-- 加载中提示，不指定，将显示默认加载中图标 -->
			<!--<img slot="loadingTip" src="path/img/loading.svg"/>-->
		</yd-infinitescroll>

		<!--这里还要判断-->
		<div class="list_2_input" v-show="navActiveNum==2&&true" slot='bottom'>
			<div class="list_2_input_left">
				<input v-model.trim="inputVal" @keyup.enter="sendMessage()" @focus="focusInput" @blur="blurtInput" type="text" placeholder="参与互动~" />
			</div>
			<!--v-show="showLiWu"-->
			<div v-show="showLiWu" class="liwu_img_f"> 
				<img  @click="openQd(false)" class="liwu_img" src="../../assets/choujiang.png" alt="" />
				<img  @click="openQd(true)" class="liwu_img" src="../../assets/qiandao.png" alt="" />
				<img  @click="openGift" class="liwu_img" src="../../assets/liwu.png" alt="" />
			</div>
			
			<div v-show="!showLiWu" class="c_size_34_48 send_btn" @click="sendMessage()">
				<div class="send_btn_c">
					发送
				</div>
			</div>
		</div>
		<div class="c_go_home c_size_30_42" @click="$router.push({name:'index',query:{str:'index'}})">去首页</div>

		<!--打开礼物-->
		<!--height="44.27%"-->
		<yd-popup v-model="giftPop" class='pop' position="bottom">
			<div v-if="showGift" class="gift_content">
				<div class="gift_list_f">
					<!--这里的gift_active要判断，暂时不知道什么规则，等待接口-->
					<div class="gift_list" @click="getSelectedGift(index,gift)" :class="giftNum==index?'gift_active':''" v-for="(gift,index) in giftList">
						<img :src="gift.icon" alt="" />
						<div class="gift_list_name">{{gift.name}}</div>
						<span class="gift_list_num">{{gift.price}}</span>
					</div>
				</div>
			</div>
			<div v-else class="money_content">
				<div class="money_content_title">{{moneyTitle}}</div>
				<ul class="money_content_list">
					<li @click="num=6" :class="num==6?'list_active':''">6</li>
					<li @click="num=30" :class="num==30?'list_active':''">30</li>
					<li @click="num=60" :class="num==60?'list_active':''">60</li>
					<li @click="num=98" :class="num==98?'list_active':''">98</li>
					<li @click="num=128" :class="num==128?'list_active':''">128</li>
					<li @click="num=188" :class="num==188?'list_active':''">188</li>
				</ul>
			</div>
			<div class="gift_btn" slot='bottom' v-if="showGift">
				<div class="gift_btn_left" @click="openCz">
					<span>充值&nbsp;（余额：{{userInfo.money}}）</span>
					<img class="jiantou" src="../../assets/jiantou.png" alt="" />
				</div>
				<div class="gift_btn_right" @click="zsBtn">赠送</div>
			</div>
			<div slot='bottom' class="money_btn" v-else>
				<div class="money_btn_btn" @click="moneyBtn">确定充值</div>
			</div>
		</yd-popup>

		<yd-popup v-model="qdPop" class='qd_pop_f' position="bottom">
			<div class="qd_pop" ref='qdRef'>
				<div class="qd_pop_top">
					<div class="qd_pop_title">{{isQd?'签到列表':'中奖记录'}}</div>
					<div v-if="isQd" class="qd_pop_label">（{{signTotal}}人已签到）</div>
					<img class="qd_pop_icon" @click="qdPop=false" src="../../assets/close_3.png" alt="" />
				</div>
				<div class="qd_list_f">
					<div class="qd_list" v-if="isQd">
						<img class="qd_list_img" :src="userInfo.avatar" alt="" />
						<div class="qd_list_right">
							<div class="qd_list_name c_text_ellipsis_1">{{userInfo.nick_name}}</div>
							<div class="qd_list_btn" v-if="isSign!=1" @click="qdClick">签到</div>
							<div class="qd_list_btn" v-else style="color: white;background: #CCCCCC;">已签到</div>
						</div>
					</div>

					<yd-infinitescroll v-show="isQd" :callback="getSignList" ref="infinitescrollDemoSign">
						<div slot="list" v-for="item in signList">
							<div  class="qd_list"  v-if='userInfo.id != item.uid'>
								<img class="qd_list_img" :src="item.avatar" alt="" />
								<div class="qd_list_right">
									<div class="qd_list_name c_text_ellipsis_1">{{item.nick_name}}</div>
									<div class="qd_list_label c_text_ellipsis_1">{{item.group_name||'无'}}</div>
								</div>
							</div>
						</div>
							
						<!-- 数据全部加载完毕显示 -->
						<span slot="doneTip">没有更多数据了~~</span>

						<!-- 加载中提示，不指定，将显示默认加载中图标 -->
						<!--<img slot="loadingTip" src="path/img/loading.svg"/>-->
					</yd-infinitescroll>

					<div v-show="!isQd">
						<yd-infinitescroll v-show='luckyList.length>0' :callback="getLuckyList" ref="infinitescrollDemoLucky">
							<div slot="list" class="qd_list " v-for="item in luckyList">
								<img class="qd_list_img" :src="item.avatar" alt="" />
								<div class="qd_list_right">
									<div class="qd_list_name c_text_ellipsis_1">{{item.nick_name}}</div>
									<div class="qd_list_label c_text_ellipsis_1">{{item.group_name||'无'}}</div>
								</div>
							</div>
							<!-- 数据全部加载完毕显示 -->
							<span slot="doneTip">没有更多数据了~~</span>

							<!-- 加载中提示，不指定，将显示默认加载中图标 -->
							<!--<img slot="loadingTip" src="path/img/loading.svg"/>-->
						</yd-infinitescroll>

						<div class="sign_no" v-if='luckyList.length==0'>抽奖暂未开始</div>
					</div>

				</div>
			</div>
		</yd-popup>
		<!--打开充值-->
		<!--<yd-popup v-model="moneyPop" position="bottom" height="60%">
            <yd-button type="warning" style="margin: 30px;" @click.native="show2 = false">Close Bottom Popup</yd-button>
        </yd-popup>-->

		<!--输入密码-->
		<PopPassword @postPassword='postPassword' :showPop.sync='showPop' :passwordNum.sync='passwordNum'></PopPassword>

	</yd-layout>
</template>

<script>
	import '../../plugins/rongyun.min.js';
	import '../../plugins/chatRoom.js';
	import PopPassword from '../../components/PopPassword/PopPassword.vue'
	import { InfiniteScroll } from 'vue-ydui/dist/lib.rem/infinitescroll';
	var pingpp = require('pingpp-js');
	import {
		Popup
	} from 'vue-ydui/dist/lib.rem/popup';

	export default {
		components: {
			[PopPassword.name]: PopPassword,
			[Popup.name]: Popup,
			[InfiniteScroll.name]: InfiniteScroll,
		},
		data() {
			return {
				roomId: 0,
				navActiveNum: 2,
				inputVal: '',
				liveInfo: {}, //直播间信息
				chatRoomObj: {},
				rongAppKey: 'pgyu6atqpmm5u',//ik1qhw09173bp cpj2xarlchhtn
				rongToken: '',
				chatRoomObj: {},
				messageList: [],
				userInfo: {},
				members: [],
				mengBanImgStyle: {},
				playBtn: true,
				outImg: true,
				palyOpen: false,
				h5VideoFlg: false,
				contentStyle: {},
				videoHeight: '',
				enterRoomJsonData: {},
				msgUserInfo: {},
				showLiWu: true,
				giftPop: false, //显示弹窗
				moneyPop: false,
				showGift: true, //弹窗中的礼物或者充值
				moneyTitle: '零钱充值',
				num: 6, //充值金额
				giftList: [],
				giftNum: 0,
				selectedGift: {},
				passwordNum: '', //分享的密码
				showPop: false, //打开密码弹窗
				passwordFlg: false, //取消密码点击播放按钮
				vipFlg: false, //取消会员点击播放按钮
				dataObj: {}, //我的信息
				outImgMsg: '', //视频文字描述
				chatHeight: '', //聊天总高度
				windowHeight: '', //聊天窗体高度
				scrollBottomHeight: '', //滚动到最底部的滚动高度
				scrollTopHeight: '', //滚动的距离位置
				msgNum: 0, //滚动信息条数,
				mySend: false,
				sessionObj: {}, //直播场次对象
				sessionId: '', //直播场次id

				pageNum: 1,
				pageCount: 10,

				courseObj: {},

				listObj: {},
				qdPop: false,
				isQd: true,
				luckyList: [],
				signList: [],
				signTotal: 0,
				pageNum_sign: 1,
				isSign:0,//1表示签到
				videoStyle:{
					height:'4.22rem'
				}
			}
		},
		created() {
			

		},
		//销毁实例
		beforeDestroy() {
			this.$root.submitEvent({
				kind: 2,
				lastFlg: true
			})
		},
		async mounted() {
			this.roomId = '' + this.$route.query.id + '';
			document.title = '直播中';
			this.sessionId = this.$route.query.sessionId
			await this.getMine()
			console.log(this.$route.query.id);
			
//			this.getcourseObj();

//						this.getSignList();
//						this.getLuckyList();
		},
		//销毁时移除
		destroyed() {

		},
		methods: {
			//获取中奖列表
			getLuckyList() {
				this.$root.ajax({
					name: 'draw/lst',
					params: {
						room_id: this.$route.query.id,
						page: this.pageNum_sign,
						count: 20,
					},
				}).then((d) => {

					for(let a = 0; a < d.data.draw_list.length; a++) {
						d.data.draw_list[a].newTime = this.$root.getDate(new Date(d.data.draw_list[a].create_time * 1000), )
					}

					this.luckyList = [...this.luckyList, ...d.data.draw_list];
					if(this.luckyList.length >= d.data.draw_total) {
						/* 所有数据加载完毕 */
						this.$refs.infinitescrollDemoLucky.$emit('ydui.infinitescroll.loadedDone');
						return;
					}

					/* 单次请求数据完毕 */
					this.$refs.infinitescrollDemoLucky.$emit('ydui.infinitescroll.finishLoad');

					this.pageNum_sign++;
				})
			},
			//获取抽奖列表
			getSignList() {
				this.$root.ajax({
					name: 'sign/lst',
					type: 'get',
					params: {
						page: this.pageNum_sign,
						count: 20,
						room_id: this.$route.query.id
					}
				}).then((d) => {
					this.isSign = d.data.is_sign
					this.signTotal = d.data.sign_total;
					
					for(let a = 0; a < d.data.sign_list.length; a++) {
						d.data.sign_list[a].newTime = this.$root.getDate(new Date(d.data.sign_list[a].create_time * 1000), )
						
					}

					this.signList = [...this.signList, ...d.data.sign_list];
					if(this.signList.length >= d.data.sign_total) {
						/* 所有数据加载完毕 */
						this.$refs.infinitescrollDemoSign.$emit('ydui.infinitescroll.loadedDone');
						return;
					}

					/* 单次请求数据完毕 */
					this.$refs.infinitescrollDemoSign.$emit('ydui.infinitescroll.finishLoad');

					this.pageNum_sign++;

				})
			},
			//直播签到
			qdClick() {
				this.$root.ajax({
					name: 'sign/signup',
					params: {
						room_id: this.$route.query.id
					},
				}).then((d) => {
					this.isSign = 1
					this.$dialog.toast({
						mes: `签到成功`,
						timeout: 1000
					});
				})
			},
			//获取直播介绍
			getcourseObj() {
				this.$root.ajax({
					name: 'course',
					params: {
						id: this.$route.query.courseId
					},
				}).then((d) => {
					this.courseObj = d.data
				})
			},
			cancelPlay() {
				this.outImg = false
				this.showPop = false
			},
			//处理金钱的0
			setMoneyZero(obj, str) {
				if(obj[str] || obj[str] === 0) {
					if((obj[str] + '').indexOf('.') >= 0) {
						return obj[str] = obj[str].toFixed(1)
					} else {
						return obj[str] = obj[str] + '.0'
					}
				}
			},
			getMine() {
				return new Promise((resolve,reject)=>{
					this.$root.ajax({
						closeAllLoading: true,
						name: 'my',
						params: {
	
						}
					}).then((d) => {
						d.data.newTime = this.$root.getDate(new Date(d.data.member_exp * 1000))
	
						d.data.money = this.setMoneyZero(d.data, 'money')
	
						this.userInfo = Object.assign({}, this.userInfo, d.data)
						this.msgUserInfo = {
							'name': this.userInfo.nick_name,
							'id': this.userInfo.id,
							'portrait': this.userInfo.avatar,
						};
						this.rongToken = this.userInfo.rc_token;
						this.getLiveRoomInfo();
					})
				})
					
			},
			//确认充值
			moneyBtn() {
				this.showGift = true;
				//				if(this.$root.config.openId) {
				//					this.payMoney();
				//				} else {
				//					this.$root.getOpenId().then(() => {
				//						this.payMoney();
				//					})
				//				}
				this.payMoney()
			},
			//打开充值
			openCz(str) {
				this.showGift = false
				this.moneyTitle = '零钱充值'
			},
			//赠送btn
			zsBtn() {
				//第一步判断，金额是否能购买礼物，如果不能购买 this.showGift=false this.moneyTitle='零钱余额不足，请先充值'
				var that = this;
				console.log(that.userInfo.money);
				console.log(that.selectedGift.price)
				if((parseFloat(that.selectedGift.price)) > (parseFloat(that.userInfo.money))) {
					that.showGift = false;
					that.moneyTitle = '零钱余额不足，请先充值';
				} else {
					that.sendGiftByMoney();
				}
			},
			sendGiftByMoney() {
				var that = this;
				that.$root.ajax({
					name: 'live/gift',
					closeAllLoading: true,
					params: {
						'token': that.$root.userInfo.token,
						'id': that.roomId,
						'gift_id': that.selectedGift.id,
						//						'session_id': that.liveInfo.sessionId,
					}
				}).then(res => {
					console.log(that.selectedGift)
					if(res.code === 0) {
						this.$dialog.toast({
							mes: `${that.selectedGift.name}赠送成功`,
							timeout: 200
						});
						this.setMoneyZero(res.data, 'balance')
						that.userInfo.money = res.data.balance;
						that.sendGiftMessage();
					}

				});
			},
			//打开签到或者抽奖
			openQd(flg) {
				this.qdPop = true
				this.pageNum_sign = 1;
				if(flg) {
					//签到
					this.isQd = true
					this.signTotal = 0;
					this.signList = [];
					this.$refs.infinitescrollDemoSign.$emit('ydui.infinitescroll.reInit');
					this.getSignList();
				} else {
					//抽奖
					this.luckyList = []
					this.$refs.infinitescrollDemoLucky.$emit('ydui.infinitescroll.reInit');
					this.getLuckyList();
					this.isQd = false
				}
			},
			//打开礼物
			openGift() {
				//每次打开重置
				this.showGift = true
				this.giftPop = true
			},
			//移开inputy
			blurtInput() {
				setTimeout(() => {
					this.showLiWu = true
				}, 200)
			},
			focusInput() {
				this.showLiWu = false;
			},
			//直播间信息
			getLiveRoomInfo() {
				var roomId = this.roomId;
				this.$root.ajax({
					name: 'live',
					params: {
						'id': this.roomId
					}
				}).then((res) => {
					res.data.newTitle = `${res.data.title}`
					//封面图
					this.mengBanImgStyle = {
						background: `url(${res.data.title_img}) no-repeat`,
						backgroundSize: `100% 100%`,
					}
//					res.data.is_computer=0
//					alert(res.data.is_computer)
					this.videoStyle={
						height:res.data.is_computer==1?'4.22rem':'5.5rem'
					}
					this.liveInfo = Object.assign({},this.liveInfo,res.data);
					
					this.$nextTick(()=>{
						this.$refs.qdRef.style.height=(window.innerHeight - this.$refs.csRef.offsetHeight) + 'px'
					})
					
					if(res.code == 0) {
						this.getEnterRoomInfoByRoomId(roomId, true);
					}
				});
			},

			getEnterRoomInfoByRoomId(roomId, flg) {
				var that = this;
				that.$root.ajax({
					name: 'live/enter',
					errormsg: true,
					closeDia: true,
					params: {
						'id': roomId,
						//						'password': this.passwordNum||that.$route.query.password,
						//						'session_id':this.sessionId||0,
					}
				}).then((res) => {
					console.log(res)
					if(res.code === 0) {

						this.$root.id = res.data.id
						this.$root.uuid = (parseInt((parseInt(new Date() - 0)) / 1000)) + '' + (this.$root.userInfo.me.id || 0)
						this.$root.submitEvent({
							kind: 2,
						})
						this.$store.commit({
							type: 'setDataEvent',
							data: {
								kind: 2,
								uuid: this.$root.uuid,
								position: 0,
								oid: res.data.id,
								uid: this.$root.userInfo && (JSON.stringify(this.$root.userInfo) != '{}') ? this.$root.userInfo.me.id : 0
							}
						})

						if(res.data.bonlive == 2) {
							that.outImg = true;
							this.outImgMsg = '主播掉线'
						} else if(res.data.bonlive === 0) {
							that.outImg = true;
							this.outImgMsg = '直播已结束'
						}
						//else{
						//分享，一次
						if(flg) {
							this.sessionObj = Object.assign({}, this.sessionObj, res.data.session)
							if(this.$root.isWeiXin()) {
								//分享
								let query = '';
								if(this.$root.config.channel){
								 	query = `params=channelDY2FGoldUrlStrDYliveRoomDetailFGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.$route.query.id}`
								}else{
								 	query = `params=oldUrlStrDYliveRoomDetailFGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.$route.query.id}`
								}
								this.$root.wxShare({
									d: {
										title: `【正在直播】${this.liveInfo.title}`,
										title_img: this.liveInfo.title_img
									}, //分享对象，题目等
									query: query, //参数
									desc: `分享嘉宾:${this.userInfo.nick_name}`
								})
							}
						}

						this.outImg = false;
						sessionStorage.setItem(`${this.$route.query.id}PasswordNum`, this.passwordNum || that.$route.query.password)
						this.passwordFlg = false
						this.vipFlg = false;
						this.showPop = false;

						that.liveInfo = Object.assign({}, that.liveInfo, {
							hls: res.data.hls,
							//							sessionId: res.data.session.id,
						})

						that.enterRoomJsonData = JSON.stringify(res.data);
						//给元素添加滚动事件
						this.$refs.messageListRef.addEventListener('scroll', this.handleScroll)

						that.enterChatRoom();
						console.log(res);
						for(let a = 0; a < res.data.gift.length; a++) {
							res.data.gift.price = this.setMoneyZero(res.data.gift[a], 'price')
						}
						that.giftList = res.data.gift;
						that.selectedGift = res.data.gift[0];
						//}

					} else if(res.code === 1011) {
						//没有会员权限
						this.vipFlg = true;
						this.showPop = false;
						this.$dialog.confirm({
							title: '温馨提示',
							mes: '该场直播需要开通会员权限才能观看',
							opts: [{
								txt: '开通会员',
								color: '#F5AB16',
								callback: () => {
									this.$router.push({
										name: 'vipOpen'
									})
								}
							}, ]
						});
					} else if(res.code === 1010) {
						//密码错误
						this.passwordFlg = true;
						if(this.passwordNum) {
							this.$dialog.toast({
								mes: `${res.msg}`,
								timeout: 1500
							});
						}
						this.showPop = true;
					} else if(res.code === 1021) {
						that.outImg = true;
						this.outImgMsg = '直播已结束'
					}
				});
			},
			enterChatRoom() {
				var that = this;
				var appInfo = {
					"appKey": that.rongAppKey,
					"token": that.rongToken
				};
				var chatRoomInfo = {
					"chatRoomId": that.roomId,
					"count": 0
				};
				RongChatRoom.init(appInfo, chatRoomInfo, {
					onSuccess: function(chatRoom) {
						that.registerRongMessage();
						var propertys = []; // 消息类中的属性名。
						that.chatRoomObj = chatRoom;
						that.sendInfoNtfMessage();
					},
					onError: function(error) {
						alert('加入聊天室失败。');
					},
					onMessage: function(message) {
						console.log(message);
						that.handleRongMessage(message);
					}
				});
			},
			//集中注册融云消息
			registerRongMessage() {
				var that = this;
				//会员消息
				var propertys = ["content", "extra", "user"];
				that.registerMessage("MemberTxtMsg", propertys);
				//进入直播间消息
				propertys = ["extra", "message", "user", "messageName"];
				that.registerMessage("InfoNtf", propertys);
				//礼物消息
				propertys = ["content", "type", "gift_id", "user"];
				that.registerMessage("GiftMsg", propertys);
			},
			//注册消息
			registerMessage(type, propertys) {
				var messageName = type; // 消息名称。
				var objectName = "RC:" + type; // 消息内置名称，请按照此格式命名 *:* 。
				var mesasgeTag = new RongIMLib.MessageTag(true, true); //true true 保存且计数，false false 不保存不计数。
				var registerRes = RongIMClient.registerMessageType(messageName, objectName, mesasgeTag, propertys);
			},
			//处理消息
			handleRongMessage(rongMessage) {
				var that = this;
				if(rongMessage.objectName == 'RC:TxtMsg' || rongMessage.objectName == "RC:MemberTxtMsg") {
					if(rongMessage.senderUserId.indexOf(that.userInfo.id + '') >= 0) {
						that.mySend = true
					} else {
						that.mySend = false
					}
				}
				let msgInfo = new Array();
				msgInfo = [];
				if(JSON.stringify(rongMessage.content.user) != {}) {
					console.log(rongMessage)
					msgInfo['msgType'] = rongMessage.objectName;
					switch(rongMessage.objectName) {
						//普通消息
						case 'RC:CompereExitMsg':
							that.quitChatRoom();
							break;
						case 'RC:InfoNtf':
							//进入直播间
							msgInfo['content'] = rongMessage.content.extra;
							break;
						case 'RC:GiftMsg':
							//进入直播间
							var msg = rongMessage.content;
							msgInfo['content'] = msg.content;
							msgInfo['name'] = msg.user.name;
							for(let a = 0; a < this.giftList.length; a++) {
								if(msg.gift_id == this.giftList[a].id) {
									msgInfo['giftImg'] = this.giftList[a].effect;
									break
								}
							}
							//msgInfo['giftImg'] = msg.type;
							break;
							//主播间重新进入直播间处理
							// case 'RC:CompereOpenMsg':
							//      window.reload();
							//     break;
						case 'RC:MemberTxtMsg':
							msgInfo['name'] = rongMessage.content.user.name + '：';
							msgInfo['content'] = rongMessage.content.content;
							break;
						case 'RC:TxtMsg':
							msgInfo['name'] = rongMessage.content.user.name + '：';
							msgInfo['content'] = rongMessage.content.content;
							break;
						case 'RC:NoticeMsg':
							msgInfo['user_name'] = rongMessage.content.message.content.user_name ;
							msgInfo['user_avatar'] = rongMessage.content.message.content.user_avatar;
							break;
					}
					(that.messageList).push(msgInfo);
					console.log(that.messageList)
					this.$nextTick(() => {
						if(this.$refs.messageListRef) {
							//聊天信息总高度
							this.chatHeight = this.$refs.messageListRef.scrollHeight

							//窗体高度
							this.windowHeight = this.$refs.messageListRef.clientHeight

							//滚动到最底部的高度为
							this.scrollBottomHeight = this.chatHeight - this.windowHeight
							console.log(this.mySend)
							//当滚动到 聊天窗体过半的以上的时候，显示下面好多条信息，
							//当滚动到 聊天窗体不过半的时候自动滚动到最底部去，不显示好多条信息，并且重置信息条数
							if(this.$refs.messageListRef.scrollTop > (this.scrollBottomHeight - (this.windowHeight / 2))) {
								this.$refs.messageListRef.scrollTop = this.scrollBottomHeight
								//通过为零的时候判断是否显示未阅读信息
								this.msgNum = 0
							} else if(this.mySend) {

								this.$refs.messageListRef.scrollTop = this.scrollBottomHeight
								//通过为零的时候判断是否显示未阅读信息
								this.msgNum = 0
							} else {
								this.msgNum++
							}
						}

					})
				}
			},
			//去底部
			goBottom() {
				this.$refs.messageListRef.scrollTop = this.scrollBottomHeight
				this.msgNum = 0
			},
			//监听滚动
			handleScroll() {
				//滚动高度
				this.scrollTopHeight = this.$refs.messageListRef.scrollTop
				if(this.$refs.messageListRef.scrollTop > (this.scrollBottomHeight - (this.windowHeight / 2))) {
					this.msgNum = 0
				}
			},
			//退出聊天室
			quitChatRoom() {
				var that = this;
				that.chatRoomObj.quit({
					onSuccess: function() {
						that.messageList = [];
						that.outImg = true;
						that.outImgMsg = '直播已结束'
						console.log("退出成功"); //退出直播间处理

					},
					onError: function(error) {
						console.log("退出失败", error)
					}
				});
			},
			navActive(num) {
				if(this.navActiveNum != num) {
					this.navActiveNum = num
					//每次切换清空
					this.inputVal = ''
				}
				if(num == 3) {
					this.pageNum = 1;
					this.members = [];
					this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.reInit');
					this.getRoomMembers();
				}
				if(num == 2) {

					this.$nextTick(() => {
						//聊天信息总高度
						this.chatHeight = this.$refs.messageListRef.scrollHeight
						//窗体高度
						this.windowHeight = this.$refs.messageListRef.clientHeight
						this.scrollBottomHeight = this.chatHeight - this.windowHeight
						this.$refs.messageListRef.scrollTop = this.scrollBottomHeight
						//通过为零的时候判断是否显示未阅读信息
						this.msgNum = 0
					})
				}
			},
			getSelectedGift(index, giftObj) {
				var that = this;
				that.giftNum = index;
				that.selectedGift = giftObj;
			},
			sendMessage() {
				var that = this;
				if(!that.inputVal) {
					that.$dialog.toast({
						mes: '发送信息不能为空',
						timeout: 2000
					});
				} else {
					//注册消息
					let pushMessage = that.inputVal;
					//会员
					if(that.userInfo.member_status == 1) {
						that.sendMemberTxtMessage(pushMessage)
					} else {
						that.sendTxtMessage(pushMessage);
					}
				}
			},
			//普通文本消息
			sendTxtMessage(pushMessage) {
				var that = this;
				//非会员
				var contentInfo = {
					content: pushMessage,
					user: that.msgUserInfo,
					extra: ''
				};
				var msg = new RongIMLib.TextMessage(contentInfo);
				if(msg != '') {
					that.pushRongYunMessage(msg);
				}
			},
			//会员发送消息
			sendMemberTxtMessage(pushMessage) {
				var that = this;
				var contentInfo = {
					content: pushMessage,
					extra: '',
					user: that.msgUserInfo,
				};
				var msg = new RongIMClient.RegisterMessage.MemberTxtMsg(contentInfo);
				if(msg != '') {
					that.pushRongYunMessage(msg);
				}
			},
			//进入直播间消息
			sendInfoNtfMessage() {
				var that = this;
				var contentInfo = {
					message: that.enterRoomJsonData,
					extra: that.userInfo.nick_name + '进入直播间',
					user: that.msgUserInfo,
					messageName: 'InformationNotificationMessage'
				};
				var msg = new RongIMClient.RegisterMessage.InfoNtf(contentInfo);
				if(msg != '') {
					that.pushRongYunMessage(msg);
				}
			},
			//发送礼物消息
			sendGiftMessage() {
				var that = this;
				var contentInfo = {
					content: that.selectedGift.name,
					type: that.selectedGift.icon,
					gift_id: that.selectedGift.id,
					user: that.msgUserInfo
				};
				var msg = new RongIMClient.RegisterMessage.GiftMsg(contentInfo);
				if(msg != '') {
					that.pushRongYunMessage(msg);
				}
			},
			pushRongYunMessage(msg) {
				var that = this;
				that.chatRoomObj.sendMessage(msg, {
					onSuccess: function(message) {

						that.handleRongMessage(message);
						that.inputVal = ''
					},
					onError: function(errorCode, message) {
						console.log("发送聊天室消息失败", errorCode);
					}
				});
			},
			getRoomMembers() {

				var that = this;
				this.$root.ajax({
					name: 'live/rank',
					params: {
						'uid': that.liveInfo.uid,
						page: this.pageNum,
						count: this.pageCount
					}
				}).then((res) => {
					for(let a = 0; a < res.data.gift_list.length; a++) {
						res.data.gift_list[a].money = this.$root.setMoneyZero(res.data.gift_list[a], 'money')
					}
					that.members = [...that.members, ...res.data.gift_list];
					if(this.members.length >= res.data.gift_total) {
						/* 所有数据加载完毕 */
						this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
						return;
					}

					/* 单次请求数据完毕 */
					this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');

					this.pageNum++;
				})

			},
			//视频播放完
			endedVideo() {
				this.outImg = true;
				this.outImgMsg = '直播异常'
			},
			pauseVideo() {
				this.palyOpen = false
			},
			//视频播放
			playIngVideo() {
				var myVideo = this.$refs.videoRef;
				myVideo.setAttribute('controls', 'controls')
				this.palyOpen = true
			},
			//播放按钮
			async playVideo() {
				var myVideo = this.$refs.videoRef;
				myVideo.play();
				myVideo.pause();
				
				var data = await this.$root.liveFlg({
					room_id: this.$route.query.id,
					name: 'liveRoom',
					msgRouter: true,
				})
				if(this.liveInfo.is_req_pwd == 1 && this.liveInfo.is_input_pwd != 1) {
					this.showPop = true;
					this.listObj = Object.assign({}, this.listObj, this.liveInfo)
					this.passwordNum = ''
					return
				}
				this.$nextTick(()=>{
					var myVideo = this.$refs.videoRef;
					myVideo.play();
					this.playBtn = false
					this.palyOpen = true
					this.h5VideoFlg = true
				})
				//myVideo.setAttribute('height',document.getElementById('app').clientHeight)
			},
			//输入密码
			async postPassword() {
				if(this.passwordNum.length == 6) {
					let o = {
						room_id: this.listObj.id,
						password: this.passwordNum,
						msgRouter: true,
						passwordFlg:true,
					};
					var data = await this.$root.liveFlg(o);
					if(data.code == 0) {
						this.showPop = false;
					}
					var myVideo = this.$refs.videoRef;
					myVideo.play();
					this.playBtn = false
					this.palyOpen = true
					this.h5VideoFlg = true

				} else {
					this.$dialog.toast({
						mes: '请根据提示正确输入',
						timeout: 1500
					});
				}
			},
			async payMoney() {
				if(this.$root.config.openId){
					
				}else{
					await this.$root.getOpenId()
				}
				var that = this;
				that.$root.ajax({
					name:'my/recharge',
					params:{
						type:0,
						channel:4,
						money:this.num,
						success_url:this.$root.config.openId
						//success_url:window.location.href,
						//success_url:`${this.$root.config.shareUrl}#/success`
					}
				}).then((d) => {
					d.data.channel = 'wx_pub'
					pingpp.createPayment(d.data, (result, err) => {
						// object 需是 Charge/Order/Recharge 的 JSON 字符串
						// 可按需使用 alert 方法弹出 log
						//console.log(JSON.stringify(object));
						if(result == "success") {
							//window.location.reload(); 
							console.log(result);
							that.userInfo.money = parseFloat(that.userInfo.money) + parseInt(that.num);
							//							that.$nextTick(()=>{
							//								setTimeout(()=>{
							//									that.getMine()
							//									alert(that.userInfo.money)
							//								},1000)
							//							})
							// 只有微信JSAPI (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)、支付宝小程序（alipay_lite）支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
						} else if(result == "fail") {
							console.log(err.msg)
							this.$dialog.toast({
								mes: err.msg,
								timeout: 1500
							});
							// Ping++ 对象 object 不正确或者微信JSAPI/微信小程序/QQ公众号支付失败时会在此处返回
						} else if(result == "cancel") {
							this.$dialog.toast({
								mes: '已取消支付！',
								timeout: 1500
							});
							// 微信JSAPI、微信小程序、QQ 公众号、支付宝小程序支付取消支付
						}
					});
				})

			}
		}
	}
</script>

<style lang="scss">
	@import './liveRoom.scss';
</style>